package com.kefu.chat.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.chat.model.ChatSession;
import com.kefu.chat.vo.ChatUserParam;
import com.kefu.common.context.KefuContext;
import com.kefu.sys.mapper.SysUserMapper;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kefu.chat.mapper.ChatLeaveMsgMapper;
import com.kefu.chat.model.ChatLeaveMsg;
import com.kefu.common.service.AbstractKefuService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 杨
 * @date 2021/12/21
 */
@Service
public class ChatLeaveMsgService  extends AbstractKefuService<ChatLeaveMsg>  {
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    protected ChatLeaveMsgMapper chatLeaveMsgMapper;

    public List<ChatLeaveMsg> leaveMsgList(ChatUserParam.UserP param) {
        List<String> ids = Lists.newArrayList();
        String UserID = param.getUserId();
        if (StrUtil.isNotBlank(UserID)) {
            ids.add(UserID);
            List<ChatLeaveMsg> list = list(Wrappers.lambdaQuery(ChatLeaveMsg.class).eq(ChatLeaveMsg::getUserId, UserID));
            if (CollUtil.isNotEmpty(list)) {
                List<String> pids = Lists.newArrayList();
                for (ChatLeaveMsg msg : list) {
                    if (StrUtil.isNotBlank(msg.getPid())) { pids.add(msg.getPid());}
                }
                if (CollUtil.isNotEmpty(pids)) {
                    List<ChatLeaveMsg> chatSessions = list(Wrappers.lambdaQuery(ChatLeaveMsg.class)
                            .in(ChatLeaveMsg::getPid, pids));
                    if (CollUtil.isNotEmpty(chatSessions)) {
                        ids.addAll(chatSessions.stream().map(ChatLeaveMsg::getUserId).collect(Collectors.toList()));
                    }
                }
            }
        }
        if (StrUtil.isNotBlank(param.getPid())) {
            List<ChatLeaveMsg> list = list(
                    Wrappers.lambdaQuery(ChatLeaveMsg.class)
                            .eq(ChatLeaveMsg::getPid, param.getPid()));
            if (CollUtil.isNotEmpty(list)) {
                ids.addAll(list.stream().map(ChatLeaveMsg::getUserId).collect(Collectors.toList()));
            }
        }
        List<ChatLeaveMsg> list = list(Wrappers.lambdaQuery(ChatLeaveMsg.class)
                .in(ChatLeaveMsg::getUserId, ids)
                .orderByDesc(ChatLeaveMsg::getCreateTime));
        Map<String, String> userMap = sysUserMapper.getUserNameMap(KefuContext.getKefuContext().getTenantId());
        list.forEach(item -> item.setUpdateUserName(userMap.get(item.getUpdateUser())));
        return list;
    }
}
